<template>
  <div style="padding:20px">
    <h1>修改密码</h1>
    <el-form label-width = "120px" :model = "model" :rules = "formRules" ref = "FormRef">
      <el-form-item label = "用户名">
        <el-input v-model="model.name" disabled></el-input>
      </el-form-item>
      <el-form-item label = "密码" prop = "pwd">
        <el-input v-model="model.pwd" type = "password" placeholder = "请输入新密码" show-password></el-input>
      </el-form-item>
      <el-form-item label = "确认密码" prop = "doublePwd">
        <el-input v-model="model.doublePwd" type = "password" placeholder = "请再次输入新密码" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type = 'primary' @click="save">保存</el-button>
      </el-form-item>
    </el-form>
 </div>
</template>

<script>
export default {
  data () {
    const password = (rule, value, cb) => {
      const regPwd = /^(?![a-zA-Z]+$)(?![0-9]+$)(?![._~!@#$^&*]+$)(?![0-9a-zA-Z]+$)(?![0-9._~!@#$^&*]+$)(?![a-zA-Z._~!@#$^&*]+$)[A-Za-z0-9._~!@#$^&*]{8,20}$/
      if (regPwd.test(value)) {
        return cb()
      }
      cb(new Error('密码必须为数字、符号、字母组成'))
    }
    return {
      model: {
        name: '',
        pwd: '',
        doublePwd: ''
      },
      formRules: {
        pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { validator: password, trigger: 'blur' }
        ],
        doublePwd: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    save () {
      this.$refs.FormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        if (this.model.doublePwd !== this.model.pwd) {
          return this.$message.error('两次密码输入不一致')
        }
        await this.$http.put('rest/Login', {
          _id: window.sessionStorage.getItem('id'),
          user: this.model.name,
          pwd: this.model.pwd
        }).then(res => {
          if (res.status !== 200) {
            return this.$message.error('修改密码失败！')
          }
          this.$message.success('修改密码成功,1秒后回到登录页面！')
          setTimeout(() => {
            this.$message.info('您的登录信息已失效，请重新登录！')
            window.sessionStorage.clear()
            this.$router.push('/login')
          }, 1000)
        })
      })
    }
  },
  created () {
    this.model.name = window.sessionStorage.getItem('user')
  }
}
</script>

<style scoped>
  .el-input{
    width:200px
  }
</style>
